//
//  CZInputKeyBoard.swift
//  微博
//
//  Created by 霸气的刘吉庆 on 16/4/26.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit

class CZInputKeyBoard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
       
        self.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        //添加子控件
        
        addSubview(toolBar)
        //设置toolBar里面的点击按钮执行的闭包
        
        //下面这里暂时没有引用self
        toolBar.emotionButtonClickClosure = {(type) in
           //点击了toolBar的按钮进行滚动
            
            //这个section对应的是button的tag
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
            //是collectionView滚动到响应的位置
            self.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            //显示对应的pageControl
            self.showPageControl(indexPath)
            
        }
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.leading.trailing.equalTo(self)
            make.height.equalTo(37)
        }
        
        addSubview(emoticonCollectionView)
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.trailing.equalTo(self)
             make.bottom.equalTo(toolBar.snp_top)
        }
        addSubview(pageControl)
        //设置约束
        //这个pageControl天然自带约束
        pageControl.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top)
            make.centerX.equalTo(toolBar)
        }
        //需要在界面完成显示之后再去移动,滚动到对应的位置,这里我们希望他滚动到默认的表情,已经走过一遍数据源方法,主线程空闲的时候去运行
        //使用多线程来执行
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            //滚动到对应的位置
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            //toolBar选中的按钮
            self.toolBar.selectedSection = indexPath.section
            //设置pageControl显示的内容
            self.showPageControl(indexPath)
            
        }
        
    }
    
    //注意在setupUI里面设置他的itemSize事没有用的
    //必须在layouts
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        //设置对应的itemSize
        //首先获取到对应的layout
        let layout = self.emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //设置itemSize
        layout.itemSize = CGSize(width:self.frame.width , height: self.frame.height - self.toolBar.frame.height)
        
        
        
    }
    
    //懒加载toolBar
    private lazy var toolBar: CZEmoticonToolBar = CZEmoticonToolBar(frame: CGRectZero)
    
    //懒加载控件,就是collectionView
    private lazy var emoticonCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        //设置layout的属性
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
        

        
        //创建一个layout
        
       let emoticonCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        emoticonCollectionView.backgroundColor = UIColor.clearColor()
        
        //设置collectionView的属性
        //注册cell
        emoticonCollectionView.registerClass(CZEmoticonViewCell.self, forCellWithReuseIdentifier: "emoticon_cell")
        
        //设置数据源
        emoticonCollectionView.dataSource = self
        emoticonCollectionView.delegate = self
        
//去掉弹簧的效果
        emoticonCollectionView.bounces = false
        
        //设置分页效果
        emoticonCollectionView.pagingEnabled = true
        //影藏滚定条
        emoticonCollectionView.showsHorizontalScrollIndicator = false
        
        return emoticonCollectionView
        
        
        
    }()
    //懒加载分页控件 pageControl
    private lazy var pageControl: UIPageControl = {
       let pageControl = UIPageControl()
        //设置属性
        //默认设置为影藏
        pageControl.hidden = true
        //选中状态
//        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        //没有选中的状态
//        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        //关闭用户交互
        pageControl.userInteractionEnabled = false
        return pageControl
    }()

}

extension CZInputKeyBoard: UICollectionViewDataSource,UICollectionViewDelegate {
    
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons.count
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //返回有多少组,直接根据单利获取对应的数据

       return CZEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons[section].count
    
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("emoticon_cell", forIndexPath: indexPath) as! CZEmoticonViewCell
//        
//        cell.backgroundColor = RandomColor
        
        cell.indexPath = indexPath
        
        
        cell.emotiocons = CZEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons[indexPath.section][indexPath.item]
       
        
        return cell
        
    }
    
    //实现代理方法,监听scrollView的滚动,首先判断当前按钮滚动到第几组,然后再去选中对应组的按钮
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //思路,如何实现呢,就是判断scrollVIew的中心点在哪里,如果在某个cell里面 ,就滚动到对应cell的组里面
        var center = scrollView.center
        //设置center.x 便于计算
        center.x = center.x + scrollView.contentOffset.x
        
        //取到当前显示的cell
        let cells = emoticonCollectionView.visibleCells()
        
        //进行判断当前的中心点在哪个cell中
        let indexPath: NSIndexPath
        
        if cells.count == 2{
            
            let firstCell = cells.first!
            let secondCell = cells.last!
            
            if CGRectContainsPoint(firstCell.frame, center) {
                indexPath = emoticonCollectionView.indexPathForCell(firstCell)!
                
                
            }else{
               indexPath = emoticonCollectionView.indexPathForCell(secondCell)!
            }
            
        }else{
            indexPath = emoticonCollectionView.indexPathForCell(cells.first!)!
        }
        
        //scrollView的位移出现问题
//        print(indexPath.section)
        toolBar.selectedSection = indexPath.section
        showPageControl(indexPath)
        
    }
    //定义一个方法,显示pageControl,需要传入indexPath 进行判断
    
    private func showPageControl(indexPath: NSIndexPath){
        
        pageControl.numberOfPages = CZEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons[indexPath.section].count
        
        //设置当前选中的page
        pageControl.currentPage = indexPath.item
        //pageControl的是否隐藏
        //如果是最近的表情,是不显示pageControl
        pageControl.hidden = indexPath.section == 0
    }
    
    
    
}
